# coding=utf-8

# v0.0.1  docker 容器内操作k8s, 请为default账号添加operator角色
import os

from kubernetes import client
import pytz
import datetime
import argparse


APISERVER = 'https://kubernetes.default.svc'

KUBERNETES_SERVICE_HOST = os.getenv('KUBERNETES_SERVICE_HOST')

SERVICEACCOUNT = '/var/run/secrets/kubernetes.io/serviceaccount'

if os.path.isdir(SERVICEACCOUNT):
    with open(os.path.join(SERVICEACCOUNT, 'namespace')) as fp:
        NAMESPACE = fp.read()

    with open(os.path.join(SERVICEACCOUNT, 'token')) as fp:
        TOKEN = fp.read()

CACERT = os.path.join(SERVICEACCOUNT, 'ca.crt')


class K8s(object):

    def __init__(self):
        configuration = client.Configuration()
        configuration.host = APISERVER
        configuration.verify_ssl = True
        configuration.ssl_ca_cert = CACERT
        configuration.api_key = {
            "authorization": "Bearer " + TOKEN
        }
        configuration.assert_hostname = KUBERNETES_SERVICE_HOST
        client.Configuration.set_default(configuration)
        self.core_v1_api = client.CoreV1Api()
        self.apps_v1_api = client.AppsV1Api()

    def restart_deployment(self, name, namespace=NAMESPACE):
        deployment = self.apps_v1_api.read_namespaced_deployment(name, NAMESPACE)
        deployment.spec.template.metadata.annotations = {
            "kubectl.kubernetes.io/restartedAt": datetime.datetime.utcnow()
            .replace(tzinfo=pytz.UTC)
            .isoformat()
        }
        resp = self.apps_v1_api.patch_namespaced_deployment(name, namespace, body=deployment)

        print("\n[INFO] deployment `%s` restarted.\n" % name)
        print("%s\t\t\t%s\t%s" % ("NAME", "REVISION", "RESTARTED-AT"))
        print(
                "%s\t%s\t\t%s\n"
                % (
                    resp.metadata.name,
                    resp.metadata.generation,
                    resp.spec.template.metadata.annotations,
                )
        )


def main():
    parser = argparse.ArgumentParser(description='k8s 操作', usage='-h 查看帮助')

    parser.add_argument('-rd', '--restart_deployment', action='append',
                        help='重启deployment: -rd "jar-test.namespace"', default=[])

    args = parser.parse_args()

    k8s = K8s()

    for deployment in args.restart_deployment:
        if deployment.find('.') == -1:
            deployment = deployment + '.' + NAMESPACE
        deployment, namespace = deployment.split('.', 1)
        k8s.restart_deployment(deployment, namespace)


if __name__ == '__main__':
    main()
